<template>
  <div class="register">
    <div class="simple-title">
      <span>{{ hexAddress }}</span>
      <el-divider></el-divider>
    </div>

    <el-form label-width="auto" :model="pointRegister" @submit.native.prevent="">
      <el-form-item label="Signed:" label-position="right" class="form-item">
        <el-input v-model.number="pointRegister.signed"></el-input>
      </el-form-item>
      <el-form-item label="Unsigned:" label-position="right" class="form-item">
        <el-input v-model.number="pointRegister.unsigned"></el-input>
      </el-form-item>
      <el-form-item label="Hex:" label-position="right" class="form-item">
        <el-input v-model="pointRegister.hex"></el-input>
      </el-form-item>
      <el-form-item label="Binary:" label-position="right" class="form-item">
        <el-input v-model="pointRegister.bin"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="SingleRegister" lang="ts">
import { computed, onMounted, ref, watch, type PropType } from "vue";
import {type IntPointRegister } from "@/types/register";
// import { editPointData } from "@/api/deviceApi";
import 'element-plus/dist/index.css'
import { TableHeader } from "@/types/device";
import { useRegisterStore } from "@/stores/register";
const registerStore = useRegisterStore();

const getIntHex = (value: number) => {
  // 参数校验（确保是16位整数）
  if (value < -32768 || value > 65535) {
    throw new Error("Value exceeds 16-bit integer range");
  }

  const buffer = new ArrayBuffer(2);
  const view = new DataView(buffer);

  // 处理有符号/无符号转换
  const uintValue = value < 0 ? 65536 + value : value;
  view.setUint16(0, uintValue, false); // 大端序写入

  // 修正补零长度（16位对应4字符十六进制）
  return "0x" + view.getUint16(0, false)
    .toString(16)
    .toUpperCase()
    .padStart(4, '0');
};

const props = defineProps({
  register: { type: Object, required: true },
   isDualRegister: { type: Boolean, required: true },
});

// 核心地址转换逻辑
const hexAddress = computed(() => {
  if (!props.isDualRegister) {
    // 单寄存器处理（完全匹配图片示例）
    const addr = props.register[TableHeader.Address];
    return registerStore.formatHex(addr);
  } else {
    // 双寄存器处理（用"-"连接）
    if (!Array.isArray(props.register)) {
      console.error('Dual decode_register mode requires array input');
      return '';
    }
    return props.register
      .map(reg => registerStore.formatHex(reg[TableHeader.Address]))
      .join('-');
  }
});

const pointRegister = ref<IntPointRegister>({
  signed: 0,
  unsigned: 0,
  hex: "",
  bin: "",
  value: 0,
});

function updateFromValue(value: number) {
  const registerValue = value;

  // 检查16位有符号数范围
  if (registerValue < -32768 || registerValue > 65535) {
    return;
  }

  // 处理有符号数表示
  let signed = registerValue;
  if (registerValue > 32767) {
    signed = registerValue - 65535;
  }

  // 处理无符号数表示
  let unsigned = registerValue;
  if (registerValue < 0) {
    unsigned = 65536 + registerValue;
  }

  // 确保数值在有效范围内
  unsigned = Math.max(0, Math.min(65535, unsigned));
  signed = Math.max(-32768, Math.min(32767, signed));

  // 格式化输出
  pointRegister.value = {
    signed: signed,
    unsigned: unsigned,
    hex: unsigned.toString(16).toUpperCase().padStart(4, '0'),
    bin: unsigned.toString(2).padStart(16, '0'),
    value: value
  };
}

watch(
  () => props.register[TableHeader.RegisterValue], // 箭头函数返回目标属性
  (newVal, oldVal) => {
    pointRegister.value.value = newVal; // 更新目标值
  }
);

// 监听所有字段的变化
watch(() => pointRegister.value.value, (newVal, oldVal) => {
  updateFromValue(newVal);
});

onMounted(() => {
  pointRegister.value.value = props.register[TableHeader.RegisterValue] || 0;
  updateFromValue(pointRegister.value.value);
});
</script>

<style lang="scss" scoped>
.register {
  margin: 2px;
  padding: 10px;
  width: 270px;
  font-family: Arial, sans-serif;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0.2, 0.2, 0.2, 0.2);
}

.simple-title {
  text-align: center;
}
.simple-title span {
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
}
.simple-title .el-divider {
  margin: 12px 0;
  background-color: #409eff;
}

.form-item {
  width: 250px;
  margin: 2px;
}

/* 使用深度选择器穿透 scoped 限制 */
:deep(.el-input__inner) {
  font-size: 16px;
  height: 25px;
}

.custom-row {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}
</style>
